package casbinx

import (
	"time"

	"gitee.com/workits/pkgs/cachex"
	"github.com/casbin/casbin/v2/persist/cache"
)

type casbinCache struct {
	cache cachex.Cache
}

func NewCasbinCache(cache cachex.Cache) *casbinCache {
	return &casbinCache{cache: cache}
}

func (c *casbinCache) Set(key string, value bool, extra ...interface{}) error {
	val := "false"
	if value {
		val = "true"
	}

	expiration := time.Duration(-1)
	if len(extra) > 0 {
		expiration = extra[0].(time.Duration)
	}
	return c.cache.Set(key, val, expiration)
}

func (c *casbinCache) Get(key string) (bool, error) {
	if val, err := c.cache.Get(key); err != nil {
		return false, err
	} else {
		if val == "true" {
			return true, nil
		}
	}
	return false, cache.ErrNoSuchKey
}

func (c *casbinCache) Delete(key string) error {
	return c.cache.Del(key)
}

func (c *casbinCache) Clear() error {
	return c.cache.Clear()
}
